package com.example.view.custom;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.viewpager.widget.ViewPager;

import com.example.common.utils.L;
import com.example.view.R;
import com.example.view.adapter.LimitlessViewPagerAdapter;

public class LimitlessViewPager extends RelativeLayout implements View.OnClickListener {

    private ViewPager vp;
    private LinearLayout ll_dot;

    public LimitlessViewPager(Context context) {
        super(context);
        initView();
    }

    public LimitlessViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public LimitlessViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public LimitlessViewPager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    //    private int[] imgIds = {R.mipmap.img1, R.mipmap.img2, R.mipmap.img3, R.mipmap.img4};
    private int[] imgIds;
    private ImageView[] dots;

    private Handler handler = new Handler();

    private void initView() {
        // 写布局 - ViewPager
        vp = new ViewPager(getContext());
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        addView(vp, params);
        // 写布局 - ll_dot
        ll_dot = new LinearLayout(getContext());
        ll_dot.setOrientation(LinearLayout.HORIZONTAL);
        ll_dot.setPadding(dp2px(20), 0, dp2px(20), 0);
        LayoutParams paramsDot = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        // 靠下
        paramsDot.addRule(ALIGN_PARENT_BOTTOM); // rule 尺子、规则
        // 靠右
        paramsDot.addRule(ALIGN_PARENT_RIGHT);
        addView(ll_dot, paramsDot);
        setOnClickListener(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        L.e("onTouchEvent");
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: // 按下
                L.e("onTouchEvent-ACTION_DOWN");
                handler.removeCallbacks(r);
                break;
            case MotionEvent.ACTION_UP: // 抬起
            case MotionEvent.ACTION_CANCEL: // 手指移除界面
                handler.postDelayed(r, 2000);
                break;
        }
        // true代表拦截触摸事件（可能造成无法手指操作滑动）
        return false;
    }

    /**
     * 开启动画，推荐在onStart时调用
     */
    public void start() {
        handler.postDelayed(r, 2000);
    }

    /**
     * 关闭动画，推荐在onStop时调用
     */
    public void stop() {
        handler.removeCallbacks(r);
    }

    /**
     * 设置无限轮播图的图片资源（只能调用一次）
     *
     * @param imgIds
     */
    public void setImgIds(int... imgIds) {
        this.imgIds = imgIds;
        dots = new ImageView[imgIds.length];
        LimitlessViewPagerAdapter adapter = new LimitlessViewPagerAdapter(imgIds);
        vp.setAdapter(adapter);

        initDot();

        int middle = adapter.getCount() / 2;
        int start = middle - middle % 4; // m:18 18-18%4 16
        vp.setCurrentItem(start, false);

        vp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                changeDot(position % LimitlessViewPager.this.imgIds.length);
            }
        });
    }

    // 初始化小圆点
    private void initDot() {
        // 先清空已加载的所有小圆点
        ll_dot.removeAllViews();
        // 创建新的小圆点
        for (int i = 0; i < imgIds.length; i++) {
            // 创建一个小圆点
            // 处理内容
            dots[i] = new ImageView(getContext());
            dots[i].setImageResource(R.drawable.selector_viewpager_dot);
            dots[i].setPadding(10, 10, 10, 10);
            // 处理布局（margin、相当于其它View的位置、）
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 50);
            ll_dot.addView(dots[i], params);
        }
        changeDot(0);
    }

    private void changeDot(int position) {
        for (int i = 0; i < dots.length; i++) {
            dots[i].setEnabled(i == position);
        }
    }

    private Runnable r = new Runnable() {
        @Override
        public void run() {
            // 跳到当前的下一张（带动画）
            vp.setCurrentItem(vp.getCurrentItem() + 1);
            handler.postDelayed(this, 2000);
            L.e("runnable");
        }
    };


    private int dp2px(float dp) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return (int) (dm.densityDpi * dp / 160 + 0.5F);
    }

    @Override
    public void onClick(View v) {

    }
}
